<template>
  <view class="group-tab" id="GROUP_TAB" :style="styleStr">
    <uni-ec-canvas class="uni-ec-canvas" id="uni-ec-canvas" ref="canvas" canvas-id="lazy-load-chart" :ec="ec"
      @atap="touchstart"></uni-ec-canvas>
    <a-btn class="reset" type="text" @tap="initChart">重置</a-btn>
    <view class="tips">
      <view class="tips-completed">已完成</view>
      <view class="tips-incompleted">未完成</view>
    </view>
  </view>
</template>

<script>
  import uniEcCanvas from '../../../uni_modules/echart/uni-ec-canvas/uni-ec-canvas'
  import {
    mapState
  } from 'vuex'

  import {
    model
  } from '@/model';

  const {
    Member
  } = model.collection;
  export default {
    components: {
      uniEcCanvas
    },
    props: {
      leaderInfo: {
        type: Object,
        default: {},
      },
      myAchieve: {
        type: Number,
        default: 0
      },
      year: {
        type: Number,
        default: 0
      },
      month: {
        type: Number,
        default: 0
      }
    },
    data() {
      const minusIcon =
        'image://'
      const plusIcon =
        'image://'
      return {
        windowH: 0,
        canvasTop: 0,
        completeColor: '#0678EC',
        incompleteColor: '#e31131',
        height: '',
        ec: {
          lazyLoad: true,
          option: {
            tooltip: {
              trigger: 'item',
              triggerOn: 'mousemove'
            },
            series: [{
              type: 'tree',
              edgeShape: 'polyline',
              height: 50,
              data: [],
              backgroundColor: '#0468ec',
              itemStyle: {
                normal: {
                  color: `${this.myAchieve >= 580 ? '#0678EC' : '#E2112F' }`,
                  borderColor: `${this.myAchieve >= 580 ? '#0678EC' : '#E2112F'}`,
                  lineStyle: {
                    color: '#999'
                  }
                }
              },
              left: '2%',
              right: '2%',
              top: 100,
              bottom: '0',
              symbol: 'circle',
              symbolSize: 15,
              orient: 'vertical',
              expandAndCollapse: true,
              label: {
                position: 'top',
                rotate: 0,
                verticalAlign: 'bottom',
                align: 'center',
                fontSize: 13,
                formatter: [
                  '{name|{b}}',
                  '{value|{@[normal]}积分}'
                ].join('\n'),
                rich: {
                  name: {
                    height: 30,
                    fontSize: 11,
                    verticalAlign: 'center',
                    backgroundColor: '#f7f7f7'
                  },
                  value: {
                    fontSize: 11,
                    backgroundColor: '#f7f7f7'
                  }
                },
                offset: [0, 64.5]
              },
              roam: true, // 平移缩放漫游
              leaves: {
                label: {
                  position: 'bottom',
                  rotate: 0,
                  verticalAlign: 'middle',
                  align: 'center',
                  fontSize: 15,
                  offset: [0, 20]
                }
              },
              animationDurationUpdate: 750
            }]
          }
        },
        params: {
          pageIndex: 1,
          pageSize: 50
        }
      }
    },
    computed: {
      styleStr() {
        let res = ''
        if (this.height) {
          res += `height: ${this.height}`
        }
        return res
      }
    },
    watch: {
      'leaderInfo': {
        handler() {
          this.init();
        },
        deep: true
      }
    },
    created() {
      this.windowH = uni.getSystemInfoSync().windowHeight
    },
    onReady() {
      this.init();
    },
    methods: {
      init() {
        this.getNodeInfo('GROUP_TAB').then((data) => {
          this.height = `calc(100vh - ${data.top}px)`
          this.canvasTop = data.top
          this.getSubDistributorList(this.leaderInfo.id).then((data) => {
            let value = this.myAchieve
            let formatData = {
              name: this.leaderInfo.text,
              value: value,
              id: this.leaderInfo.id,
              collapsed: false,
              children: data.map((o) => {
                let f = this.formatEcData(o)
                f.collapsed = true
                f.idChain = this.leaderInfo.id + '-' + o.id
                return f
              }),
              idChain: this.leaderInfo.id + '',
              label: {
                position: 'top',
                align: 'center',
                offset: [0, 0],
                rich: {
                  name: {
                    lineHeight: 30,
                    height: 30,
                    backgroundColor: 'transparent',
                    color: this.getColor(this.myAchieve)
                  },
                  value: {
                    lineHeight: 10,
                    height: 10,
                    backgroundColor: 'transparent',
                    color: this.getColor(this.myAchieve)
                  }
                }
              },
              itemStyle: {
                normal: {
                  color: `${this.myAchieve >= 580 ? '#0678EC' : '#E2112F' }`,
                  borderColor: `${this.myAchieve >= 580 ? '#0678EC' : '#E2112F'}`,
                  lineStyle: {
                    color: '#999'
                  }
                }
              }
            }
            this.ec.option.series[0].data = [formatData]
            setTimeout(() => {
              this.initChart()
            }, 1500)
          })
        })
      },
      initChart() {
        this.$refs.canvas.init()
      },
      setOption(val, notMerge, lazyUpdate) {
        this.$refs.canvas.$curChart.setOption(val, notMerge, lazyUpdate)
      },
      clearChart() {
        this.$refs.canvas.$curChart.clear()
      },
      getChartOption() {
        return this.$refs.canvas.$curChart.getOption()
      },
      chartResize(opts) {
        this.$refs.canvas.$curChart.resize(opts)
      },
      getChartHeight(offset = 0) {
        let nodes = this.$refs.canvas.$curChart._chartsViews[0]._data.tree._nodes
        let depthestExpandNode = nodes.reduce((val, el) => {
          return el.depth > val.depth ? el : val
        }, nodes[0])
        return (depthestExpandNode.depth + offset) * 130
      },
      touchstart(e) {
        let idChainArr = e.data.idChain.split('-')
        // findNode
        let option = this.getChartOption()
        let arr = option.series[0].data,
          count = 0,
          target = {}
        while (count < idChainArr.length) {
          let curId = idChainArr[count]
          target = arr.find(d => d.id == curId)
          if (target) {
            arr = target.children
          } else {
            count = idChainArr.length
          }
          count++
        }
        let type = e.event.type
        if (type == 'click') {
          if (e.data.children.length == 0) {
            this.getSubDistributorList(e.data.id).then((data) => {
              if (data.length == 0) {
                this.toast('暂无下级~')
                return
              }
              data.forEach((o) => {
                let f = this.formatEcData(o)
                f.idChain = target.idChain + '-' + o.id
                target.children.push(f)
              })
              target.collapsed = false
              // let option = this.getChartOption()//this.ec.option//
              // let nodes = this.$refs.canvas.$curChart._chartsViews[0]._data.tree._nodes
              // let depthestExpandNode = nodes.reduce((val,el) => {
              //   return el.depth>val.depth ? el:val
              // },nodes[0])
              // option.series[0].height = 50 + (depthestExpandNode.depth)*100
              option.series[0].height = this.getChartHeight()
              this.$nextTick(() => {
                this.setOption(option, true, true)
              })
            })
          } else {
            // 普通点击关闭
            target.collapsed = !target.collapsed
            option.series[0].height = this.getChartHeight()

            this.$nextTick(() => {
              this.setOption(option, true, true)
            })
          }
        }
      },
      getSubDistributorList(id) {
        if (!id) return
        return Member.sendApi('page', {
          params: this.params,
          data: {
            query: {
              isQueryAchieve: 1,
              distributorPId: id,
              year: this.year,
              month: this.month
            }
          }
        }).then(res => {
          const {
            status,
            data
          } = res;
          return status ? data : [];
        })
      },
      formatEcData(obj) {
        let data = {
          name: obj.nickname,
          id: obj.id,
          value: obj.integral || 0,
          children: [],
          collapsed: true
        }
        data.label = {
          rich: {
            value: {
              color: this.getColor(data.value)
            }
          }
        }
        data.itemStyle = {
          color: `${data.value >= 580 ? '#0678EC' : '#E2112F' }`,
          borderColor: `${data.value >= 580 ? '#0678EC' : '#E2112F' }`,
          lineStyle: {
            color: '#999'
          }
        }
        return data
      },
      findNode(id) {
        let arr = this.ec.option.series[0].data
      },
      getColor(value) {
        return value >= 580 ? this.completeColor : this.incompleteColor
      }
    }
  }
</script>

<style lang="less">
  .group-tab {
    position: relative;

    .uni-ec-canvas {
      width: 100%;
      height: 100%;
      display: block;
    }

    .reset {
      position: absolute;
      left: 0;
      top: 0;
    }

    .tips {
      position: absolute;
      top: 0;
      right: @box-gap;

      .tips-completed,
      .tips-incompleted {
        position: relative;
        font-size: 32rpx;
        font-weight: 500;
        color: #333;

        &::before {
          content: "";
          position: absolute;
          left: -40rpx;
          top: 50%;
          transform: translateY(-50%);
          width: 30rpx;
          height: 30rpx;
          border-radius: 50%;
        }
      }

      .tips-completed::before {
        background: #0678ec;
      }

      .tips-incompleted::before {
        background: #e31131;
      }
    }
  }
</style>